﻿using AIVision.Model.EntityModels;
using AIVision.Repository.Entitys;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIVision.Repository.Services
{
    public class PLCConfigService
    {
        private readonly AiVisionDbContext dbContext;
        private readonly IMapper mapper;

        public PLCConfigService(AiVisionDbContext dbContext, IMapper mapper) 
        {
            this.dbContext = dbContext;
            this.mapper = mapper;
        }

        public PLCConfigDto GetPLCConfig()
        {
           var entity = dbContext.PLCConfigs.FirstOrDefault();
            if (entity == null)
                entity = new Entitys.PLCConfig() { IP="127.0.0.1"};
            return mapper.Map<PLCConfigDto>(entity);
        }
        public bool SavePLCConfig(PLCConfigDto model)
        {

            var newentity = mapper.Map<PLCConfig>(model);

            var entity = dbContext.PLCConfigs.FirstOrDefault(m=>m.Id== model.Id);
            if(entity != null)
                dbContext.Entry(entity).CurrentValues.SetValues(newentity);
            else
                dbContext.PLCConfigs.Add(newentity);
            dbContext.SaveChanges();
            return true;
        }
    }
}
